//路由守卫
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from './store/modules/user'
import pinia from './store'
import setting from './setting'

//获取用户仓库
const userStore = useUserStore(pinia)
// 全局前置守卫
router.beforeEach(async (to, _from, next) => {
  document.title = `${setting.title}- ${to.meta.title}`
  nprogress.start()
  //获取token
  const token = userStore.token
  //获取用户信息
  const username = userStore.username
  //用户登录
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        //获取用户信息
        try {
          await userStore.userInfo()
          next({ ...to })
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
        } catch (error) {
          //清除用户信息
          await userStore.userLoginout()
          // 跳转到登录页
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //用户未登录
    // 路径是登录页面
    if (to.path === '/login') {
      // 放行
      next()
    } else {
      // 指向登录页
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// 全局后置守卫
// eslint-disable-next-line @typescript-eslint/no-unused-vars
router.afterEach((_to, _from) => {
  nprogress.done()
})
